package com.tcp2.net;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Author: 杨俊辉
 * Time: 2014-09-25 11:29
 * Copyright (C) 2014 Xiamen Yaxon Networks CO.,LTD.
 */
public class PlatformChannel {

    protected static Logger logger = LoggerFactory.getLogger(PlatformChannel.class);


    private volatile int connectState = CS_CLOSED; //连接状态
    private static final int CS_CLOSED = 0;
    private static final int CS_CONNECTED = 1;
    private Channel channel;
    private AtomicLong lastContactTime = new AtomicLong(0);
    private final Lock connectLock = new ReentrantLock(false);

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        if (this.channel != null && !this.channel.equals(channel)) {
            this.channel.close();
        }
        this.channel = channel;
    }

    public int getConnectState() {
        return connectState;
    }

    public void setConnectState(int connectState) {
        this.connectState = connectState;
    }

    public AtomicLong getLastContactTime() {
        return lastContactTime;
    }

    public void setLastContactTime(AtomicLong lastContactTime) {
        this.lastContactTime = lastContactTime;
    }

    protected void connnected() {
        connectLock.lock();
        connectState = CS_CONNECTED;
        lastContactTime.set(System.currentTimeMillis());
        connectLock.unlock();
    }

    protected void disconnected(Channel ch) {
        connectLock.lock();
        if (this.channel != null && this.channel.equals(ch)) {
            this.channel = null;
            connectState = CS_CLOSED;
            lastContactTime.set(0);
        }
        connectLock.unlock();
    }

    protected void checkAlive() {
        lastContactTime.set(System.currentTimeMillis());
    }


}
